<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getexamListService,
  deleteExamService,
  publishExamService,
  cancelPublishExamService,
} from "@/api/competition";
import router from "@/router";

const loading = ref(false);
const params = reactive({
  pageNum: 1,
  pageSize: 10,
  title: "",
});
const datetimeRange = ref([]);
const competitionList = ref([]);
const total = ref(0);

// 获取竞赛列表
const getCompetitionList = async () => {
  loading.value = true;
  try {
    // 如果有日期范围，添加到参数中
    const requestParams = { ...params };
    if (datetimeRange.value && datetimeRange.value.length === 2) {
      requestParams.startTime = datetimeRange.value[0];
      requestParams.endTime = datetimeRange.value[1];
    }

    const result = await getexamListService(requestParams);
    console.log("API响应:", result);
    competitionList.value = result.rows;
    total.value = result.total;
  } catch (error) {
    console.error("获取竞赛列表失败:", error);
    ElMessage.error("获取竞赛列表失败");
  } finally {
    loading.value = false;
  }
};

// 初始化加载竞赛列表
getCompetitionList();

// 分页处理
function handleSizeChange(newSize) {
  params.pageSize = newSize;
  params.pageNum = 1;
  getCompetitionList();
}
function handleCurrentChange(newPage) {
  params.pageNum = newPage;
  getCompetitionList();
}

// 搜索竞赛
const onSearch = () => {
  params.pageNum = 1;
  getCompetitionList();
};

// 重置搜索条件
const onReset = () => {
  // 重置表单
  Object.keys(params).forEach((key) => {
    if (key !== "pageNum" && key !== "pageSize") {
      params[key] = "";
    }
  });
  datetimeRange.value = [];
  params.pageNum = 1;
  // 重新加载所有竞赛数据
  getCompetitionList();
  ElMessage.success("搜索条件已重置");
};

// 添加竞赛
const onAddCompetition = () => {
  router.push("/oj/layout/updateExam?type=add");
};

// 判断竞赛是否未开始
const isNotStartExam = (row) => {
  return new Date(row.startTime) > new Date();
};

// 编辑竞赛
const onEdit = (id) => {
  router.push(`/oj/layout/updateExam?type=edit&examId=${id}`);
};

// 删除竞赛
const onDelete = (id) => {
  ElMessageBox.confirm("确认删除该竞赛吗？删除后不可恢复", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await deleteExamService(id);
        ElMessage.success("删除成功");
        getCompetitionList();
      } catch (error) {
        console.error("删除竞赛失败:", error);
        ElMessage.error("删除竞赛失败");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 发布竞赛
const publishExam = (id) => {
  ElMessageBox.confirm("确认发布该竞赛吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(async () => {
      try {
        await publishExamService(id);
        ElMessage.success("发布成功");
        getCompetitionList();
      } catch (error) {
        console.error("发布竞赛失败:", error);
        ElMessage.error("发布竞赛失败");
      }
    })
    .catch(() => {
      // 用户取消发布
    });
};

// 撤销发布竞赛
const cancelPublishExam = (id) => {
  ElMessageBox.confirm("确认撤销发布该竞赛吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await cancelPublishExamService(id);
        ElMessage.success("撤销发布成功");
        getCompetitionList();
      } catch (error) {
        console.error("撤销发布失败:", error);
        ElMessage.error("撤销发布失败");
      }
    })
    .catch(() => {
      // 用户取消撤销发布
    });
};
</script>

<template>
  <div class="competition-manage">
    <div class="header">
      <h2>竞赛管理</h2>
    </div>

    <!-- 搜索表单区域 -->
    <div class="search-form">
      <el-form inline="true">
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="datetimeRange"
            style="width: 240px"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="竞赛名称">
          <el-input
            v-model="params.title"
            placeholder="请您输入要搜索的竞赛名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="onSearch" plain>搜索</el-button>
          <el-button @click="onReset" plain type="info">重置</el-button>
          <el-button type="primary" plain @click="onAddCompetition"
            >添加竞赛</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table height="526px" :data="competitionList" v-loading="loading">
      <el-table-column prop="title" label="竞赛标题" />
      <el-table-column prop="startTime" width="180px" label="竞赛开始时间" />
      <el-table-column prop="endTime" width="180px" label="竞赛结束时间" />
      <el-table-column label="是否开赛" width="100px">
        <template #default="{ row }">
          <div v-if="!isNotStartExam(row)">
            <el-tag type="warning">已开赛</el-tag>
          </div>
          <div v-else>
            <el-tag type="info">未开赛</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" width="100px" label="是否发布">
        <template #default="{ row }">
          <div v-if="row.status == 0">
            <el-tag type="danger">未发布</el-tag>
          </div>
          <div v-if="row.status == 1">
            <el-tag type="success">已发布</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createName" width="140px" label="创建用户" />
      <el-table-column prop="createTime" width="180px" label="创建时间" />
      <el-table-column label="操作" width="180px">
        <template #default="{ row }">
          <el-button
            v-if="isNotStartExam(row)"
            type="text"
            @click="onEdit(row.examId)"
            >编辑
          </el-button>
          <el-button
            v-if="isNotStartExam(row)"
            type="text"
            @click="onDelete(row.examId)"
            class="red"
            >删除
          </el-button>
          <el-button
            v-if="row.status == 1 && isNotStartExam(row)"
            type="text"
            @click="cancelPublishExam(row.examId)"
            >撤销发布</el-button
          >
          <el-button
            v-if="row.status == 0 && isNotStartExam(row)"
            type="text"
            @click="publishExam(row.examId)"
            >发布</el-button
          >
          <el-button type="text" v-if="!isNotStartExam(row)"
            >已开赛，不允许操作</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        background
        size="small"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:current-page="params.pageNum"
        v-model:page-size="params.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.competition-manage {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #2a6fc7;
    }
  }

  .search-form {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #f0f2f5;
    border-radius: 6px;

    .el-form {
      margin-bottom: 0;
    }

    .el-form-item {
      margin-right: 16px;
      margin-bottom: 0;
    }

    .el-input__wrapper {
      border-radius: 4px;
    }
  }

  :deep(.el-table) {
    --el-table-header-bg-color: #2a6fc7;
    --el-table-header-text-color: #ffffff;
    --el-table-border-color: #e4e7ed;

    .el-table__header-wrapper {
      .el-table__header {
        th {
          font-weight: normal;
          background-color: #2a6fc7;
          color: #ffffff;
        }
      }
    }
    .el-pagination {
      margin-top: 20px;
      justify-content: flex-end;

      .el-pager li.is-active {
        background-color: #2a6fc7 !important;
      }
    }
    .el-table__body {
      tr {
        height: 48px;
      }

      td {
        padding: 8px 0;
        color: #303133;
      }
    }

    .action-btn {
      margin-right: 8px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>
